package me.ingxin.android.tools.app.sysbar

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatDialog
import me.ingxin.android.tools.app.utils.logD
import me.ingxin.android.sysbar.InsetsWatcher
import me.ingxin.android.sysbar.getSystemBarsHeight
import me.ingxin.android.sysbar.immersion
import me.ingxin.android.tools.app.R
import me.ingxin.android.tools.app.databinding.DialogSysBarBinding
import java.lang.Integer.min

/**
 * Created by ingxin on 2022/8/10
 * 通过R.style.MyDialog样式修改,可以解决dialog window操作的相关问题
 */
class SysBarDialog(context: Context) : AppCompatDialog(context, R.style.MyDialog) {

    private lateinit var binding: DialogSysBarBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding =
            DialogSysBarBinding.inflate(layoutInflater, window?.decorView as? ViewGroup, false)
        setContentView(binding.root)
        supportActionBar?.hide()

        window?.immersion()
        window?.statusBarColor = Color.TRANSPARENT
        window?.navigationBarColor = Color.TRANSPARENT

        binding.outView.setOnClickListener { dismiss() }

        initViews()
        InsetsWatcher(binding.tv)
            .onIMEAnimationCallback(binding.et) {
                logD("键盘顶部距离dialog底部$it")
                val navH = binding.et.getSystemBarsHeight().second
                val d = min(navH - it, 0)
                binding.root.translationY = d.toFloat()
            }
            .launch()
    }

    private fun initViews() {
        //设置window背景色和间距,观察整个window区域
//        window?.setBackgroundDrawable(ColorDrawable(Color.RED))
//        window?.decorView?.setPadding(10, 10, 10, 10)

        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.decorView?.setPadding(0, 0, 0, 0)

        window?.attributes?.let {
            it.width = ViewGroup.LayoutParams.MATCH_PARENT
            it.height = ViewGroup.LayoutParams.MATCH_PARENT
            it.gravity = Gravity.BOTTOM
        }
    }


}